const {getUserInfo} = require("../service/user.service")
const {userNoExist,userPasswordFalse,TokenExpiredError,JsonWebTokenError} = require("../constant/err.type")
const jwt = require("jsonwebtoken");
const {TOKEN_KEY} = require("../config/default")
const bcrypt = require("bcryptjs");
// 1.用户名不存在。2.密码错误
const verifyLogin = async (ctx,next)=>{
    const {password} = ctx.request.body;
    const res = await getUserInfo(ctx.request.body)
    if(res.length<=0) {
        ctx.app.emit("error",userNoExist,ctx);
        return;
    }else {
        // console.log(res,"middleware--")
        const isTrue =  bcrypt.compareSync(password,res[0].password); // true
        if(!isTrue) {
            return ctx.app.emit("error",userPasswordFalse,ctx);
        }
        ctx.user = res[0];
    }
    await next();
}

const verifyToken = async (ctx,next)=>{
    const {authorization} = ctx.request.header;
    
    try {
        const token = authorization;
        console.log(token,"--token");
        const res =  jwt.verify(token,TOKEN_KEY);
        ctx.user = res;
        // console.log("jwttoken携带的数据",res);
    } catch (error) {
        console.log(error,"errorrrrr")
        switch(error.name){
            case 'TokenExpiredError':
                ctx.app.emit("error",TokenExpiredError,ctx);break;
            default:
                ctx.app.emit("error",JsonWebTokenError,ctx);
        }
        return 
    }
    await next();
}




module.exports = {verifyLogin,verifyToken};